package org.cqipc.edu.utils;

import org.apache.commons.io.FilenameUtils;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * @Description: 文件操作工具类
 * @ClassNmae: FileUtils
 * @Author: HeYue
 * @DateTime: 2020-11-01 18:09
 **/
public class FileUtils {
    //限制5M大小
    private static final long FILESIZEMAX = 5242880;


    public static String FileUpload(MultipartFile file) throws IOException {
        if (file.isEmpty()) {
            return "../../upload/images/log.png";
        }
        if (file.getSize() > FILESIZEMAX) {
            return "error_size";
        }
        String extension = "." + FilenameUtils.getExtension(file.getOriginalFilename());
        String newFileName =
                new SimpleDateFormat("yyyyMMssHHmmss").format(new Date()) + UUID.randomUUID().toString().replace("-", "") + extension;
        String classPath = ResourceUtils.getURL("").getPath() + "src/main/resources/upload";
        String dateDir = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        String uploadPath = classPath + "/" + dateDir;
        File uploadPathFile = new File(uploadPath);
        if (!uploadPathFile.exists())
            uploadPathFile.mkdirs();
        file.transferTo(new File(uploadPathFile, newFileName));
        return "../../upload/" + dateDir + "/" + newFileName;


    }

    public static String FileDownload(MultipartFile fileinfo, HttpSession session) throws IOException {
        return null;
    }


}
